import java.net.URL;

import com.vmware.vim25.Event;
import com.vmware.vim25.EventFilterSpec;
import com.vmware.vim25.mo.EventHistoryCollector;
import com.vmware.vim25.mo.EventManager;
import com.vmware.vim25.mo.ServiceInstance;

/**
 * http://vijava.sf.net
 * @author Steve Jin
 */

public class QueryHistoricalEvents 
{  
  public static void main(String[] args) throws Exception
  {
	  String[] temp = new String[]{"https://10.16.2.59/sdk","root","vmware"};
	    ServiceInstance si = new ServiceInstance(
	        new URL(temp[0]), temp[1], temp[2], true);

    EventManager evtMgr = si.getEventManager();

    if(evtMgr!=null)
    {
      EventFilterSpec eventFilter = new EventFilterSpec();
      EventHistoryCollector ehc = 
        evtMgr.createCollectorForEvents(eventFilter);
      
      int total = 0;
      
      Event[] latestEvts = ehc.getLatestPage();
      printEvents(latestEvts, 0);
      total += latestEvts==null? 0 : latestEvts.length;
      
      System.out.println("\nBefore Latest Page:");
      ehc.resetCollector();
      while(true)
      {
        Event[] events = ehc.readPreviousEvents(50);
        if(events==null)
        {
          break;
        }
        printEvents(events, total);
        total += events.length;
      }
    }
    si.getServerConnection().logout();
  }
  
  static void printEvents(Event[] events, int total)
  {
    for(int i=0; i<events.length; i++)
    {
      System.out.println("Event[" + (total+i) + "]=" + events[i].getFullFormattedMessage());
      System.out.println("Event: " + events[i].getCreatedTime().getTime());
    }
  }
}